#!/bin/sh 
#set -x

if [  $# == 1  ]; then
  DAYS=1095
elif [ $# == 2 ]; then
  DAYS=$2
else
  echo "Usage: makeCert test.example.org [days]" 
  echo "       makeCert alice@example.org [days]"
  echo "days is how long the certificate is valid"
  echo "days set to 0 generates an invalid certificate"
  exit 0
fi

DOMAIN=`echo $1 | perl -ne '{print "$1\n" if (/\.(.*)$/)}'   ` 
ADDR=$1

echo "making cert for ${DOMAIN} ${ADDR}"

rm -f ${ADDR}_*.pem
rm -f ${ADDR}.p12

case ${ADDR} in
*:*) ALTNAME="URI:${ADDR}" ;;
*@*) ALTNAME="URI:sip:${ADDR},URI:im:${ADDR},URI:pres:${ADDR}" ;;
*)   ALTNAME="DNS:${DOMAIN},DNS:${ADDR},URI:sip:${ADDR}" ;;
esac
 
#ALTNAME="URI:sip:pekka.nrc.sipit.net,URI:sip:nrc.sipit.net"

rm -f demoCA/index.txt
touch demoCA/index.txt
rm -f demoCA/newcerts/*

export ALTNAME

openssl genrsa  -out ${ADDR}_key.pem 2048
openssl req -new  -config openssl.cnf -reqexts cj_req \
        -sha256 -key ${ADDR}_key.pem \
        -out ${ADDR}.csr -days ${DAYS} <<EOF
US
California
San Jose
sipit

${ADDR}



EOF

if [ $DAYS == 0 ]; then
openssl ca -extensions cj_cert -config openssl.cnf \
    -passin pass:password -policy policy_anything \
    -md sha256 -batch -notext -out ${ADDR}_cert.pem \
    -startdate 990101000000Z \
    -enddate 000101000000Z \
     -infiles ${ADDR}.csr
else
openssl ca -extensions cj_cert -config openssl.cnf \
    -passin pass:password -policy policy_anything \
    -md sha256 -days ${DAYS} -batch -notext -out ${ADDR}_cert.pem \
     -infiles ${ADDR}.csr
fi

openssl pkcs12 -passin pass:password \
    -passout pass:password -export \
    -out ${ADDR}.p12 -in ${ADDR}_cert.pem \
    -inkey ${ADDR}_key.pem -name ${ADDR} -certfile demoCA/cacert.pem

openssl x509 -in ${ADDR}_cert.pem -noout -text

case ${ADDR} in
*@*) mv ${ADDR}_key.pem user_key_${ADDR}.pem; \
     mv ${ADDR}_cert.pem user_cert_${ADDR}.pem ;;
*)   mv ${ADDR}_key.pem domain_key_${ADDR}.pem; \
     mv ${ADDR}_cert.pem domain_cert_${ADDR}.pem ;;
esac
